package com.android.view.hqview;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.android.app.CommonType;
import com.android.model.entity.eventbus.BusUtils;
import com.android.model.entity.res.QuoteKLineBean;
import com.android.model.info.LocalSp;
import com.android.presenter.HqKLinePresenter;
import com.android.presenter.contract.HqKLinesContract;
import com.android.util.DateUtils;
import com.android.util.HqDefaultValue;
import com.android.util.HqKlineDb;
import com.android.util.HqUtils;
import com.android.util.JsonUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mp.chart.charts.KLineChart;
import com.mp.chart.charts.KLineCombinedChart;
import com.mp.chart.components.YAxis;
import com.mp.chart.data.AJData;
import com.mp.chart.data.BarData;
import com.mp.chart.data.BarDataSet;
import com.mp.chart.data.BarEntry;
import com.mp.chart.data.CandleData;
import com.mp.chart.data.Entry;
import com.mp.chart.data.KLineData;
import com.mp.chart.data.LineData;
import com.mp.chart.data.LineDataSet;
import com.mp.chart.data.MinutesData;
import com.mp.chart.formatter.DataFormatter;
import com.mp.chart.formatter.DateFormatter;
import com.mp.chart.formatter.YValueFormatter;
import com.mp.chart.listener.OnMarketSelectValueListener;
import com.mp.chart.markerview.HighValueMarkerView;
import com.mp.chart.markerview.HightCircleMarkerView;
import com.mp.chart.markerview.IndexMarkerView;
import com.mp.chart.markerview.LeftMarkerView;
import com.mp.chart.markerview.LowValueMarkerView;
import com.mp.chart.markerview.MAMarkerView;
import com.mp.chart.markerview.QuoteInfoMarkerView;
import com.mp.chart.markerview.RightMarkerView;
import com.mp.chart.markerview.XAxisMarkerView;
import com.mp.chart.model.ADX;
import com.mp.chart.model.ATR;
import com.mp.chart.model.DMI;
import com.mp.chart.model.KDJ;
import com.mp.chart.model.MACD;
import com.mp.chart.model.RSI;
import com.mp.chart.model.VOL;
import com.mp.chart.utils.StringUtils;
import com.mp.chart.utils.VolumeUtils;
import com.android.R;


import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;


/**
 * K线公用View
 * Created by TenFace on 17/10/25.
 */

public class KLineView extends BaseChartView implements HqKLinesContract.View, OnMarketSelectValueListener, IndexView.OnIndexSelected {
    private KLineCombinedChart mKLineCombinedChart;
    private HqKlineDb hqKlineDb;
    private HqKLinePresenter mPresenter;
    private ArrayList<KLineData> kLineDatas;
    private IndexView mIndexView;
    private SparseArray<String> showXLabels = new SparseArray<>();
    private ArrayList<String> xVolume = new ArrayList<>();
    private List<KLineData> mKData = new ArrayList<>();
    private boolean isFullScreen;
    private FrameLayout chartTopHigh;
    private String upColor, downColor, equalColor, tvColor;
    private String adjust = IndexModel.MAJUST;
    private String topType = IndexModel.MAJUST;
    private String mBottomIndexType = IndexModel.IX_VOL;
    private TextView highTime, highOpen, highHigh, highLow, highClose, highFu;
    private View highlightLayout;
    private String name, typeLine;
    private List<MinutesData> minutesDatas = new ArrayList<>();
    private boolean isScroll;
    private int num;
    private List<QuoteKLineBean.DataBean> dataBeanList;
    private String URL = "";
    private String symbol = "";
    private String historicalQuoteInterval = "";
    private String adjustmentMethod = "";
    private long endDate;
    private int timeNumber;
    private String date = "";
    private String indexType;
    private boolean noRefresh = false;
    int isMoveToLastType = 0;
    private String indexTopType = "";
    private String indexBottomType = IndexModel.IX_VOL;//底部图标的类型，默认是成交量
    private int selectXIndex = 0;
    private int visiableMax = 0;
    private List<VOL> volList;
    private List<MACD> macdList;
    private List<KDJ> kdjList;
    private List<RSI> rsiList;
    private List<ADX> adxList;
    private List<ATR> atrList;


    public KLineView(Context context, FrameLayout v, Bundle bundle, int num) {
        super(context, bundle);
        this.chartTopHigh = v;
        this.num = num;
    }

    @Override
    public int getLayoutId() {
        return R.layout.chart_kline;
    }

    @Override
    public void initLayout(Context context) {
        mKLineCombinedChart = (KLineCombinedChart) findViewById(R.id.klineChart);
        mIndexView = (IndexView) findViewById(R.id.indexView);
        mIndexView.setOnIndexSelected(this);
        name = mBundle.getString("name");
        typeLine = mBundle.getString("typeLine");
        isScroll = mBundle.getBoolean("isScroll");
        isFullScreen = mBundle.getBoolean("fullScreen");
        initChart();
        initTabHighLightView();
    }

    /**
     * 初始化横屏顶部的view
     */
    private void initTabHighLightView() {
        highlightLayout = LayoutInflater.from(getContext()).inflate(R.layout.hq_highlight_layout, null);
        highTime = (TextView) highlightLayout.findViewById(R.id.highTime);
        highOpen = (TextView) highlightLayout.findViewById(R.id.highOpen);
        highHigh = (TextView) highlightLayout.findViewById(R.id.highHigh);
        highClose = (TextView) highlightLayout.findViewById(R.id.highClose);
        highLow = (TextView) highlightLayout.findViewById(R.id.highLow);
        highFu = (TextView) highlightLayout.findViewById(R.id.highFu);
    }

    @Override
    public void initData() {

        hqKlineDb = new HqKlineDb(getContext());


        adjust = hqKlineDb.getTopIndex();
        mBottomIndexType = hqKlineDb.getBottomIndex();
        if (!isFullScreen) {
            mIndexView.setVisibility(GONE);
            mKLineCombinedChart.setDrawYLabels(false);
        } else {
            mIndexView.setVisibility(VISIBLE);
            mKLineCombinedChart.setDrawYLabels(false);
            mKLineCombinedChart.setYAxisLabelCount(5);
        }
        mKLineCombinedChart.setIsFullScreen(isFullScreen);
        mPresenter = new HqKLinePresenter(getContext(), "", typeLine, "", this, mKLineCombinedChart);
        mPresenter.setKLinesTime(typeLine);
    }

    /**
     * 初始化图表
     */
    private void initChart() {
        upColor = DataFormatter.colorToString(LocalSp.getInstance(getContext()).getBeginColor());
        downColor = DataFormatter.colorToString(LocalSp.getInstance(getContext()).getEndColor());
        equalColor = DataFormatter.colorToString(getResources().getColor(R.color.mainFontColor));
        tvColor = DataFormatter.colorToString(getResources().getColor(R.color.mainFontColor));

        mKLineCombinedChart.setDrawYLabels(false);
        mKLineCombinedChart.setDrawXLabels(true);
        mKLineCombinedChart.setTouchEnable(true);
        //mKLineCombinedChart.setVisibleXRange(30, 60);
        mKLineCombinedChart.setVisiableMin(5);
        mKLineCombinedChart.setMAColor(getResources().getColor(R.color.ma5),
                getResources().getColor(R.color.ma10),
                getResources().getColor(R.color.ma30));
        mKLineCombinedChart.setHighlightColor(getResources().getColor(R.color.highlight));
        mKLineCombinedChart.setDrawBorder(getResources().getColor(R.color.main_title_bg), 1f);
//        mKLineCombinedChart.setWaitingColor(getResources().getIntArray(R.array.waitingColor));
        mKLineCombinedChart.setGridLineColor(getResources().getColor(R.color.main_title_bg));
        mKLineCombinedChart.setXAxisLabelColor(getResources().getColor(R.color.main_text));
        mKLineCombinedChart.setYAxixLabelColor(getResources().getColor(R.color.main_text));

        mKLineCombinedChart.setYValueFormatter(new YValueFormatter("#0.00"));
//        mKLineCombinedChart.setLeftRightOffset(Utils.convertDpToPixel(10), Utils.convertDpToPixel(10));
        mKLineCombinedChart.setYAxixPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        mKLineCombinedChart.setYAxisOffset(2);


        mKLineCombinedChart.setIncreasingPaintStyle(Paint.Style.FILL);//阴阳K线图都是实心
        mKLineCombinedChart.setDecreasingPaintStyle(Paint.Style.FILL);
        mKLineCombinedChart.setXAxisValueFormat(new DateFormatter(typeLine));

        if (!typeLine.equals(CommonType.TIME_TYPE_MIN)) {
            mKLineCombinedChart.setHighLowValueMarkerView(new HighValueMarkerView(getContext(), R.layout.share_marker_view),
                    new LowValueMarkerView(getContext(), R.layout.share_marker_view));
        }

        mKLineCombinedChart.setLRMarkerView(
                new QuoteInfoMarkerView("kline", getContext(), R.layout.quote_info_markerview, false),
                new LeftMarkerView("kline", getContext(), R.layout.share_marker_view, false, "#0.00"),
                new RightMarkerView("kline", getContext(), R.layout.share_marker_view, false, "#0.00"),
                new XAxisMarkerView(getContext(), R.layout.share_marker_view, "kline"), isFullScreen);

        mKLineCombinedChart.setLMarkerView(new LeftMarkerView("kline", getContext(), R.layout.share_marker_view, true, "#0.00"));

        mKLineCombinedChart.getAffilateChart().setValueMarkerView(new IndexMarkerView(getContext(), R.layout.mamarkerview));

//        mKLineCombinedChart.setMaxVolumeMarkerView(new TopMarkerView("kline" ,getContext(), R.layout.share_marker_view, false, 0));

        mKLineCombinedChart.setValueMarkerView(new MAMarkerView(getContext(), R.layout.mamarkerview), isFullScreen);

        mKLineCombinedChart.setHighLightCircle(new HightCircleMarkerView(getContext(), getResources().getColor(R.color.highlight)));
        mKLineCombinedChart.setXMarkerView(new XAxisMarkerView(getContext(), R.layout.share_marker_view, typeLine));
        mKLineCombinedChart.setOnMarketSelectValueListener(this);
        mKLineCombinedChart.setOnChartGestureListener(this);
        mKLineCombinedChart.clearKLineData();
        mKLineCombinedChart.restoreAffilateChart();//初始化bottom
//        mKLineCombinedChart.setTopOnClickListener(new KLineCombinedChart.TopOnClickListener() {
//            @Override
//            public void OnClick(int p, TextView textView) {
//                String tv;
//                if (adjust.equals(IndexModel.MAJUST)) {//如果当前是ma,则切换boll
//                    adjust = IndexModel.BOLLJUST;
//                    tv = adjust + "(" + hqKlineDb.getBOLL1() + "," + hqKlineDb.getBOLL2() + ")";
//                    EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));//保证只在MA的时候接收snap的数据，刷新图表
//                } else {
//                    adjust = IndexModel.MAJUST;
//                    tv = adjust + "(" + hqKlineDb.getMA1() + "," + hqKlineDb.getMA2() + "," + hqKlineDb.getMA3() + ")";
//                    EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(true));
//                }
//
//                textView.setText(tv);
//                mIndexView.changeAdjust(adjust);
//                hqKlineDb.setTopIndex(adjust);
//            }
//        });


    }

    @Override
    public void onValueSelected(int xIndex, Entry klineEntry, Entry barEntry) {
        selectXIndex = xIndex;
        //下面两行代码用以保证长按时只能响应长按的手势
        // 1.发消息通知依附的activity，关闭刷新
        // 2.请求不允许其他手势打断这个手势
        EventBus.getDefault().post(new BusUtils.refreshStatus(false));
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(true);

        //只有当前选中的index是最后一条的时候，才去接收snap的数据，并且更新数据和图表
        if (xIndex == dataBeanList.size() - 1) {
            EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(true));
            Log.e("quote--", "xIndex=" + xIndex + ".==." + (dataBeanList.size() - 1));
        } else {
            EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
        }

        //当选中的是最后一条的时候，启动timer去刷新TopHighView
        //TODO
//        try {
//            if (isFullScreen) {
//                if (selectXIndex == dataBeanList.size() - 1) {
//                    quoteStockTimer.start();
//                } else {
//                    MarketDataResult.DataBean dataBean = dataBeanList.get(dataBeanList.size() - 1 - selectXIndex);
//                    syncTopHighView(selectXIndex, dataBean);
//                    quoteStockTimer.cancel();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    @Override
    public void updateLine(List<QuoteKLineBean.DataBean> kLineChartBean, int moveToLastType) {
        isMoveToLastType = moveToLastType;
        mKLineCombinedChart.restoreScale();
        kLineDatas = new ArrayList<>();
        dataBeanList = kLineChartBean;
        setChartData(dataBeanList, 0);
        refreshBottomChart(indexBottomType);
        if (isMoveToLastType == 0) {
            mKLineCombinedChart.moveToLast();
        }
        mKLineCombinedChart.syncKlineChart();
        mKLineCombinedChart.syncAffilateChart();
        mKLineCombinedChart.invalidate();
    }

    @Override
    public IndexView getIndexView(Context context) {
        return mIndexView;
    }

    /**
     * 设置K线图的数据
     *
     * @param chartBean 传入请求到的K线的数据
     * @param isMove    是否移动到最后
     */
    private void setChartData(List<QuoteKLineBean.DataBean> chartBean, int isMove) {

//        try {
        kLineDatas.clear();
        minutesDatas.clear();
        int maxShow = 0;

        if (chartBean.size() >= 1000) {
            maxShow = 1000;
        } else {
            maxShow = chartBean.size() - 1;
        }

        for (int i = maxShow; i >= 0; i--) {
            KLineData kLineData = new KLineData();
            MinutesData minutesData = new MinutesData();
            QuoteKLineBean.DataBean info = chartBean.get(i);
            kLineData.close = (float) info.getClose().doubleValue();
            minutesData.close = (float) info.getClose().doubleValue();
            kLineData.open = (float) info.getOpen().doubleValue();
            minutesData.open = (float) info.getOpen().doubleValue();
            kLineData.high = (float) info.getHigh().doubleValue();
            minutesData.high = (float) info.getHigh().doubleValue();
            kLineData.low = (float) info.getLow().doubleValue();
            minutesData.low = (float) info.getLow().doubleValue();
            kLineData.vol = (float) info.getVolume().doubleValue();
            minutesData.chengjiaoliang = (float) info.getVolume().doubleValue();

            int increasingColor = LocalSp.getInstance(getContext()).getBeginColor();
            int decreasingColor = LocalSp.getInstance(getContext()).getEndColor();

            if (kLineData.close == kLineData.open && kLineData.high == kLineData.low && kLineData.close == kLineData.high) {
                minutesData.color = increasingColor;
                minutesData.barStyle = Paint.Style.FILL;
            } else if (kLineData.close == kLineData.open) {
                minutesData.color = increasingColor;
                minutesData.barStyle = Paint.Style.FILL;
            } else if (kLineData.close < kLineData.open) {
                minutesData.color = decreasingColor;
                minutesData.barStyle = Paint.Style.FILL;
            } else if (kLineData.close > kLineData.open) {
                minutesData.color = increasingColor;
                minutesData.barStyle = Paint.Style.FILL;
            }
            if (typeLine.equals(CommonType.TIME_TYPE_MIN)) {
                if (i == 0) {
                    kLineData.percent = 0;
                    kLineData.lastClose = (float) info.getOpen().doubleValue();

                } else {
                    QuoteKLineBean.DataBean infoLast = chartBean.get(i - 1);
                    BigDecimal changeNow = info.getClose().subtract(infoLast.getClose());
                    kLineData.percent = changeNow.divide(infoLast.getClose(), 4, BigDecimal.ROUND_HALF_UP).floatValue();
                    kLineData.lastClose = infoLast.getClose().floatValue();
                }
                kLineData.date = DateUtils.getDateToMDHm(chartBean.get(i).getCloseDateTime());
                minutesData.date = DateUtils.getDateToMDHm(chartBean.get(i).getCloseDateTime());

            } else if (typeLine.equals(CommonType.TIME_TYPE_ONE_MIN) || typeLine.equals(CommonType.TIME_TYPE_ONE_HOUR) || typeLine.equals(CommonType.TIME_TYPE_DAY)) {
                kLineData.percent = (float) info.getChangePercent().doubleValue();
                kLineData.lastClose = (float) info.getPreviousClose().doubleValue();
                kLineData.date = DateUtils.getDateToStringYMD(chartBean.get(i).getCloseDate());
                minutesData.date = DateUtils.getDateToStringYMD(chartBean.get(i).getCloseDate());
            }

            showXLabels.put(chartBean.size() - 1 - i, kLineData.date);

            String time = DateUtils.getDateToStringYM(info.getCloseDate());
            xVolume.add(time + "");

            kLineDatas.add(kLineData);
            minutesDatas.add(minutesData);
        }
        int type = hqKlineDb.getSelectDataIndex();
        int sumType = hqKlineDb.getSelectAverageIndex();

        kLineDatas = HqUtils.getmovingAverage(kLineDatas, type, sumType, HqDefaultValue.MA1);
        kLineDatas = HqUtils.getmovingAverage(kLineDatas, type, sumType, HqDefaultValue.MA2);
        kLineDatas = HqUtils.getmovingAverage(kLineDatas, type, sumType, HqDefaultValue.MA3);


        mKLineCombinedChart.setShowXLabels(showXLabels);

        mIndexView.changeAdjust(topType);
        mIndexView.changeIndex(mBottomIndexType);

        if (!StringUtils.isEmpty(indexType != null)) {
            buildChart(kLineDatas, indexType, isMove);
        }

        if (isMoveToLastType == 0) {
            mKLineCombinedChart.moveToLast();
        }
        mKLineCombinedChart.syncKlineChart();
        mKLineCombinedChart.syncAffilateChart();
        mKLineCombinedChart.invalidate();

        stop();//关闭加载菊花
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    /**
     * 获取新的数据，进行分页加载
     */
    public void getLeftData() {

        if (dataBeanList == null || dataBeanList.size() == 0) {
            return;
        }
        switch (typeLine) {

            case "day":

                URL = "";
                historicalQuoteInterval = "DAY";
                adjustmentMethod = "ALL";
                endDate = dataBeanList.get(dataBeanList.size() - 2).getCloseDate();
                timeNumber = 90 * 2;
                date = historicalQuoteInterval;
                break;

            case "week":

                URL = "";
                historicalQuoteInterval = "WEEK";
                adjustmentMethod = "ALL";
                endDate = dataBeanList.get(dataBeanList.size() - 2).getCloseDate();
                timeNumber = 90 * 2;
                date = historicalQuoteInterval;
                break;

            case "month":

                URL = "";
                historicalQuoteInterval = "MONTH";
                adjustmentMethod = "ALL";
                endDate = dataBeanList.get(dataBeanList.size() - 2).getCloseDate();
                timeNumber = 90 * 2;
                date = historicalQuoteInterval;
                break;
        }

        ArrayList<Object> params = new ArrayList<>();
        params.add(symbol);
        params.add(historicalQuoteInterval);
        params.add(adjustmentMethod);
        params.add(endDate);
        params.add(timeNumber);
        params.add(date);
        Gson gson = new Gson();

        if (!StringUtils.isEmpty(URL)) {
            OkGo.post(URL)
                    .upString(gson.toJson(params))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            QuoteKLineBean quoteKLineBean = JsonUtil.parseJsonToBean(s, QuoteKLineBean.class);
                            EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                            if (quoteKLineBean != null) {
                                String status = quoteKLineBean.getStatus();
                                if (status.equals(CommonType.STATUS_TYPE_QUOTE_SUCCESS)) {
                                    List<QuoteKLineBean.DataBean> dataList = new ArrayList<>();
                                    dataList.addAll(quoteKLineBean.getData());
                                    if (dataList.size() > 2) {
                                        dataBeanList.addAll(dataList);

                                        //如果需要更新数据（包含增删改），需执行以下操作
                                        // 1.清理chart（此处clearChart并非是真的清理，只是暂时从屏幕中隐藏，如果有相同的数据，会显示并继续画图），并刷新视图
                                        mKLineCombinedChart.clearChart();
                                        mKLineCombinedChart.syncKlineChart();
                                        mKLineCombinedChart.syncAffilateChart();
                                        mKLineCombinedChart.invalidate();

                                        //2.设置K线图的数据，isMove不移动到last
                                        setChartData(dataBeanList, 1);

                                        //3.设置成交量bar图表的数据，由于设置了图表联动，bar图表是否移动到last由K线图来控制，注意此处bar图表包含各种指标（VOL，M A C D，KDJ，RSI，ADX,ATR）
                                        refreshBottomChart(indexBottomType);

                                        //4.刷新视图
                                        mKLineCombinedChart.syncKlineChart();
                                        mKLineCombinedChart.syncAffilateChart();
                                        mKLineCombinedChart.invalidate();

                                    }
                                    canTranslate = true;
                                } else {
                                    canTranslate = true;
                                }
                            } else {
                                canTranslate = true;
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            canTranslate = true;
                            EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                        }

                    });
        }
    }

    /**
     * 刷新顶部的tab
     *
     * @param xIndex 当前选中的柱状图的index
     * @param kData  数据源
     */
    private void syncTopHighView(int xIndex, QuoteKLineBean.DataBean kData) {
//        if (kData == null) {
//            return;
//        }
//        try {
//            double baseClose;
//            if (xIndex == 0) {
//                baseClose = kData.getOpen().doubleValue();
//            } else {
//                baseClose = kLineDatas.get(xIndex - 1).close;
//            }
//
//            if (xIndex == kLineDatas.size() - 1) {
//                noRefresh = true;
//            } else {
//                noRefresh = false;
//            }
//
//            String color = kData.getOpen() > baseClose ? upColor : (kData.getOpen() == baseClose ? equalColor : downColor);
//            highTime.setText(DateUtils.getDateToStringYMD(kData.getCloseDate()));
//
//            highOpen.setText(Html.fromHtml(String.format("<font color='%s'>开</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(kData.getOpen()))));
//
//            color = kData.getHigh() > baseClose ? upColor : (kData.getHigh() == baseClose ? equalColor : downColor);
//            highHigh.setText(Html.fromHtml(String.format("<font color='%s'>高</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(kData.getHigh()))));
//
//            color = kData.getClose() > baseClose ? upColor : (kData.getClose() == baseClose ? equalColor : downColor);
//            highClose.setText(Html.fromHtml(String.format("<font color='%s'>收</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(kData.getClose()))));
//
//            highFu.setText(Html.fromHtml(String.format("<font color='%s'>涨跌</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(0.388) + "%")));
//
//            color = kData.getLow() > baseClose ? upColor : (kData.getLow() == baseClose ? equalColor : downColor);
//            highLow.setText(Html.fromHtml(String.format("<font color='%s'>低</font>&nbsp;<font color='%s'>%s</font>", tvColor, color, StringUtils.doubleToDoubleString(kData.getLow()))));
//
//
//            chartTopHigh.removeAllViews();
//            chartTopHigh.addView(highlightLayout);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onValueNothing() {
        //与onValueSelected回调保持对应，用以保证长按结束后其他手势的正常操作
        // 1.发消息通知依附的activity，可以刷新
        // 2.请求允许其他手势操作
        EventBus.getDefault().post(new BusUtils.refreshStatus(true));
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(false);

        //只有当前选中的index是最后一条的时候，才去接收snap的数据，并且更新数据和图表
        try {
            if (dataBeanList != null && dataBeanList.size() > 0 && visiableMax == dataBeanList.size() - 1) {
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(true));
            }
            selectXIndex = 0;
            //如果是横屏，onValueNothing的时候，顶部的tabView需要隐藏
            if (isFullScreen) {
                chartTopHigh.removeAllViews();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    public void networkError() {

    }

    @Override
    public void onAdjustSelected(IndexModel model) {
        if (!isScroll)
            mKLineCombinedChart.stopChart();
        mKLineCombinedChart.clearKLineData();

        indexType = model.type;
        buildChart(kLineDatas, indexType, 0);
        hqKlineDb.setTopIndex(indexType);
        mKLineCombinedChart.setChartIndexStr(indexType);//设置右上方文字指标
    }

    /*MACD、KDJ、RSI、DMI、DMA、WR、PSY、CR、ARBR、CCI、BIAS*/
    @Override
    public void onIndexSelected(IndexModel model) {
        if (!isScroll)
            mKLineCombinedChart.stopChart();

        mKLineCombinedChart.restoreAffilateChart();
        final String type = model.type;
        indexBottomType = type;
        mKLineCombinedChart.clearAffilateData();
        hqKlineDb.setBottomIndex(type);
        mKLineCombinedChart.setBottomChartIndexStr(type);
        if (kLineDatas == null)
            return;
        refreshBottomChart(indexBottomType);
        mKLineCombinedChart.syncKlineChart();
        mKLineCombinedChart.syncAffilateChart();  //非自动刷新下与k线看齐
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {
        super.onChartLongPressed(me);
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(true);
    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {
        super.onChartDoubleTapped(me);
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(true);
    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {
        super.onChartSingleTapped(me);
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(true);
    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {
        super.onChartFling(me1, me2, velocityX, velocityY);
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(true);
    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {
        super.onChartScale(me, scaleX, scaleY);
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(true);
    }

    boolean canTranslate = true;//控制每次滑动只请求一次数据

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {
        super.onChartTranslate(me, dX, dY);
        mKLineCombinedChart.requestDisallowInterceptTouchEvent(true);
        try {
            //bar左上角的成交量显示为当前图表显示的所有数据中的最大成交量，一屏显示90条
            float maxVolume = mKLineCombinedChart.getAffilateChart().getYMax();
            mKLineCombinedChart.setVolume("成交量:" + VolumeUtils.getVolUnit(maxVolume));

            Log.e("quote-", "----dataBeanList.size==" + (dataBeanList.size() - 1) + "----dx=" + dX + "----dy=" + dY + "--maxVolume" + maxVolume);

            visiableMax = mKLineCombinedChart.getVisiableMax();

            //最后一条K线刷新的处理
            // 1.如果图表向右滑，最后一条K线滑出屏幕外的时候，停止接收snap的数据，停止刷新数据
            // 2.如果最后一条K线显示在当前屏幕中，并且图表中选中的是MA，BarChart选中的是成交量，才开始接收snap的数据，并且启动刷新（目前刷新只在MA和成交量里启动，后期优化）

            if (visiableMax < dataBeanList.size() - 1) {

                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));

            } else if (visiableMax == dataBeanList.size() - 1 && IndexModel.MAJUST.equals(indexTopType) && IndexModel.IX_VOL.equals(indexBottomType)) {
                if (selectXIndex == 0 || selectXIndex == dataBeanList.size() - 1) {
                    EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(true));
                } else {
                    EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                }
            }

            Log.e("quote", "getTransX==" + mKLineCombinedChart.getViewPortHandler().getTransX() + "----dX==" + dX);

            //分页请求并加载数据的逻辑
            //  需要满足以下条件，才去加载数据，以避免图表加载异常
            //      1.当检测到MotionEvent为正在move的状态；
            //      2.并且检测到图表滑动到了左边的尽头；
            //      3.并且手势滑动的距离超过了300；
            //      4.canTranslate的状态为true（Tips：canTranslate的状态默认为true，触发分页加载时立刻置为false，在分页请求成功或者失败的回调里置为true）
            if (me.getAction() == MotionEvent.ACTION_MOVE && mKLineCombinedChart.getViewPortHandler().getTransX() == 0 && dX > 300 && canTranslate) {
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                canTranslate = false;
                getLeftData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新底部图表
     *
     * @param type 当前选中的IndexView的类型，默认是成交量
     */
    private void refreshBottomChart(String type) {
        switch (type) {
            case IndexModel.IX_VOL:
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(true));

                if (volList != null && volList.size() > 0) {
//                List<MACD> macdList = HqUtils.getMACD(kLineDatas, HqDefaultValue.MACD1, HqDefaultValue.MACD2, HqDefaultValue.MACD3);
                    volList.clear();
                }
                volList = HqUtils.getVol(minutesDatas, HqDefaultValue.MA1, HqDefaultValue.MA2, HqDefaultValue.MA3);
//                initChart();
//                buildChart(kLineDatas, indexType);
                buildVol2(volList, minutesDatas);

                try {
                    //初始化bar图表的成交量初始值
                    float initVolume = mKLineCombinedChart.getAffilateChart().getYMax();
                    mKLineCombinedChart.setVolume("成交量:" + VolumeUtils.getVolUnit(initVolume));
                } catch (Exception e) {
                    e.printStackTrace();
                }

//                mKLineCombinedChart.syncKlineChart();
//                mKLineCombinedChart.syncAffilateChart();  //非自动刷新下与k线看齐
//                mKLineCombinedChart.moveToLast();
//                buildVol(minutesDatas);

                break;
            case IndexModel.IX_MACD:
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                if (macdList != null && macdList.size() > 0) {
                    macdList.clear();
                }
                macdList = HqUtils.getMACD(kLineDatas, HqDefaultValue.MACD1, HqDefaultValue.MACD2, HqDefaultValue.MACD3);
                buildMACD(macdList);
                break;
            case IndexModel.IX_KDJ:
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                if (kdjList != null && kdjList.size() > 0) {
                    kdjList.clear();
                }
                kdjList = HqUtils.getKDJ(kLineDatas, HqDefaultValue.K, HqDefaultValue.D, HqDefaultValue.J);
                buildKDJ(kdjList);
                break;
            case IndexModel.IX_RSI:
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                if (rsiList != null && rsiList.size() > 0) {
                    rsiList.clear();
                }
                rsiList = HqUtils.getRsi(kLineDatas, HqDefaultValue.RSI1, HqDefaultValue.RSI2, HqDefaultValue.RSI3);
                buildRSINow(rsiList);
                break;
            case IndexModel.IX_ADX:
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                if (adxList != null && adxList.size() > 0) {
                    adxList.clear();
                }
                adxList = HqUtils.getAdx(kLineDatas, 9);
                buildADX(adxList);
                break;

            case IndexModel.IX_ATR:
                EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
                if (atrList != null && atrList.size() > 0) {
                    atrList.clear();
                }
                atrList = HqUtils.getAtr(kLineDatas, 15);
                buildATR(atrList);
                break;
            default:
                break;
        }
    }

    private void setLineDateSetStyle(LineDataSet dataSet) {
        dataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        dataSet.setDrawCircles(false);
        dataSet.setDrawValues(false);
        dataSet.setLineWidth(1f);
    }

    /**
     * 初始化K线
     *
     * @param kLineDatas K线的数据源
     * @param type       顶部选中的类型
     * @param move       是否要moveToLast
     */
    private void buildChart(List<KLineData> kLineDatas, String type, int move) {

        this.mKData = kLineDatas;
        if (mKData.size() == 0) {
            mKLineCombinedChart.setNoDataText("暂无数据");
            return;
        }
        isMoveToLastType = move;
        indexTopType = type;
        mKLineCombinedChart.setShowXLabels(showXLabels);

        ArrayList<KLineData> temp = new ArrayList<>(kLineDatas);

        if (IndexModel.MAJUST.equals(type)) {
            mKLineCombinedChart.setData(temp, move, typeLine);
            EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(true));
        } else {
            mKLineCombinedChart.setBollData(HqUtils.getMaBOLL(temp, HqDefaultValue.BOLL1, HqDefaultValue.BOLL2), move,typeLine);
            EventBus.getDefault().post(new BusUtils.KLineRefreshStatus(false));
        }

 /*       List<MACD> macdList = HqUtils.getMACD(temp);
        buildMACD(macdList);*/

        mKLineCombinedChart.performClick();
//        mKLineCombinedChart.moveToLast();
        mKLineCombinedChart.syncKlineChart();
        mKLineCombinedChart.syncAffilateChart();
        mKLineCombinedChart.invalidate();


    }

    private void buildVol2(List<VOL> volList, List<MinutesData> minutesDatas) {
        final KLineChart affilateChart = mKLineCombinedChart.getAffilateChart();
        //affilateChart.getAxisLeft().setDrawGridLines(false);

        affilateChart.getAxisLeft().setStartAtZero(true);


        affilateChart.getAxisLeft().enableGridDashedLine(3.0f, 3.0f, 3.0f);
        affilateChart.getAxisLeft().setDrawGridLines(true);


//        ArrayList<MinutesData> minutesDatas = kLineDatas.getBarData();
        int count = volList.size();

        List<String> xVals = Arrays.asList(new String[count]);
        ArrayList<BarEntry> barEntries = new ArrayList<>();
        ArrayList<Entry> line1 = new ArrayList<>();
        ArrayList<Entry> line2 = new ArrayList<>();
        ArrayList<Entry> line3 = new ArrayList<>();
        float max = 0;
        for (int i = 0; i < count; i++) {
            MinutesData minutesData = minutesDatas.get(i);
            VOL vol = volList.get(i);
            barEntries.add(new BarEntry(minutesData.chengjiaoliang, i, minutesData));
            max = Math.max(max, minutesData.chengjiaoliang);
            line1.add(new Entry(vol.ma5, i, vol));
            line2.add(new Entry(vol.ma10, i, vol));
            line3.add(new Entry(vol.ma30, i, vol));
        }

        if (max > 0) {
//            String volJishu = DataFormatter.getVolJishu(max);

            affilateChart.getAxisLeft().setShowOnlyMax(" ");

            mKLineCombinedChart.setVolume("VOL：" + VolumeUtils.getVolUnit(max));

//            mKLineCombinedChart.getAffilateChart().setButtonView(new TopMarkerView("kline", getContext(), R.layout.mamarkerview, false, max));

//            if (volJishu.equals("股")) {
//                affilateChart.getAxisLeft().setValueFormatter(new ChengJiaoLiangFormatter((int) Math.pow(10, 0)));
//            } else if (volJishu.equals("万股")) {
//                affilateChart.getAxisLeft().setValueFormatter(new ChengJiaoLiangFormatter((int) Math.pow(10, 4)));
//            } else if (volJishu.equals("亿股")) {
//                affilateChart.getAxisLeft().setValueFormatter(new ChengJiaoLiangFormatter((int) Math.pow(10, 8)));
//            }
        }


        BarDataSet barDataset = new BarDataSet(barEntries, "成交量");
        barDataset.setAxisDependency(YAxis.AxisDependency.LEFT);


        LineDataSet lineDataset1 = new LineDataSet(line1, "MA5");
        LineDataSet lineDataset2 = new LineDataSet(line2, "MA10");
        LineDataSet lineDataset3 = new LineDataSet(line3, "MA30");
        setLineDateSetStyle(lineDataset1);
        setLineDateSetStyle(lineDataset2);
        setLineDateSetStyle(lineDataset3);

        lineDataset1.setColor(getResources().getColor(R.color.ma5));
        lineDataset2.setColor(getResources().getColor(R.color.ma10));
        lineDataset3.setColor(getResources().getColor(R.color.ma30));

        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(lineDataset1);
        lineDatasets.add(lineDataset2);
        lineDatasets.add(lineDataset3);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);

        AJData marketData = new AJData(xVals);
        BarData barData = new BarData(xVals, barDataset);
        marketData.setData(barData);
        marketData.setData(lineData);
        mKLineCombinedChart.setAffilateChartData(marketData);
        mKLineCombinedChart.setInitScale(xVals);

    }

    private void buildMACD(List<MACD> macdList) {


        List<String> xVals = Arrays.asList(new String[macdList.size()]);
        ArrayList<BarEntry> barEntries = new ArrayList<>();
        //ArrayList<MACD> data = kData.getMACD();
        ArrayList<Entry> line1 = new ArrayList<>();
        ArrayList<Entry> line2 = new ArrayList<>();
        int count = macdList.size();
        if (count == 0) {
            mKLineCombinedChart.setAffilateChartNoDataText("暂无数据");
            return;
        }

        for (int i = 0; i < count; i++) {
            MACD d = macdList.get(i);
            MinutesData minutesData = new MinutesData();

            minutesData.color = d.macd < 0 ?
                    LocalSp.getInstance(getContext()).getBeginColor() :
                    LocalSp.getInstance(getContext()).getEndColor();
            minutesData.barStyle = Paint.Style.FILL;
            barEntries.add(new BarEntry(d.macd, i, minutesData));
            line1.add(new Entry(d.dif, i, d));
            line2.add(new Entry(d.dea, i, d));

        }
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setShowBaseValueAndMaxmin(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setYlabelStatic(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setLabelCount(3);
        AJData combinedData = new AJData(xVals);
        BarDataSet barDataset = new BarDataSet(barEntries, "macd");
        BarData barData = new BarData(xVals, barDataset);
        barData.setDrawValues(false);

        LineDataSet lineDataset1 = new LineDataSet(line1, "dif");

        LineDataSet lineDataset2 = new LineDataSet(line2, "dea");

        setLineDateSetStyle(lineDataset1);
        setLineDateSetStyle(lineDataset2);

        lineDataset1.setColor(getResources().getColor(R.color.dif));
        lineDataset2.setColor(getResources().getColor(R.color.dea));

        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(lineDataset1);
        lineDatasets.add(lineDataset2);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);

        combinedData.setData(lineData);
        combinedData.setData(barData);
        combinedData.setData(new CandleData());

        mKLineCombinedChart.setAffilateChartData(combinedData);
        mKLineCombinedChart.setInitScale(xVals);

    }

    private void buildKDJ(List<KDJ> kdjList) {
        List<String> xVals = Arrays.asList(new String[kdjList.size()]);
        ArrayList<Entry> k = new ArrayList<>();
        ArrayList<Entry> d = new ArrayList<>();
        ArrayList<Entry> j = new ArrayList<>();


        int count = kdjList.size();

        if (count == 0) {
            mKLineCombinedChart.setAffilateChartNoDataText("暂无数据");
            return;
        }
        for (int i = 0; i < count; i++) {
            KDJ kdj = kdjList.get(i);
            k.add(new Entry(kdj.k, i, kdj));
            d.add(new Entry(kdj.d, i, kdj));
            j.add(new Entry(kdj.j, i, kdj));

        }


        LineDataSet KLineDataSet = new LineDataSet(k, "k");
        LineDataSet DLineDataSet = new LineDataSet(d, "d");
        LineDataSet JLineDataSet = new LineDataSet(j, "j");

        setLineDateSetStyle(KLineDataSet);
        setLineDateSetStyle(DLineDataSet);
        setLineDateSetStyle(JLineDataSet);

        KLineDataSet.setColor(getResources().getColor(R.color.k));
        DLineDataSet.setColor(getResources().getColor(R.color.d));
        JLineDataSet.setColor(getResources().getColor(R.color.j));


        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(KLineDataSet);
        lineDatasets.add(DLineDataSet);
        lineDatasets.add(JLineDataSet);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);


        AJData combinedData = new AJData(xVals);


        combinedData.setData(lineData);
        combinedData.setData(new CandleData());
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setLabelCount(3);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setYlabelStatic(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setStartAtZero(false);
        mKLineCombinedChart.setAffilateChartData(combinedData);
        mKLineCombinedChart.setInitScale(xVals);

    }

    private void buildRSINow(List<RSI> rsiList) {

        List<String> xVals = Arrays.asList(new String[rsiList.size()]);
        ArrayList<Entry> rsi1 = new ArrayList<>();
        ArrayList<Entry> rsi2 = new ArrayList<>();
        ArrayList<Entry> rsi3 = new ArrayList<>();


        int count = rsiList.size();

        if (count == 0) {
            mKLineCombinedChart.setAffilateChartNoDataText("暂无数据");
            return;
        }
        for (int i = 0; i < rsiList.size(); i++) {
            RSI r = rsiList.get(i);
            rsi1.add(new Entry(r.rsi1, i, r));
            rsi2.add(new Entry(r.rsi2, i, r));
            rsi3.add(new Entry(r.rsi3, i, r));

        }


        LineDataSet rsi1LineDataSet = new LineDataSet(rsi1, "rsi1");
        LineDataSet rsi2LineDataSet = new LineDataSet(rsi2, "rsi2");
        LineDataSet rsi3LineDataSet = new LineDataSet(rsi3, "rsi3");

        setLineDateSetStyle(rsi1LineDataSet);
        setLineDateSetStyle(rsi2LineDataSet);
        setLineDateSetStyle(rsi3LineDataSet);

        rsi1LineDataSet.setColor(getResources().getColor(R.color.rsi1));
        rsi2LineDataSet.setColor(getResources().getColor(R.color.rsi2));
        rsi3LineDataSet.setColor(getResources().getColor(R.color.rsi3));


        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(rsi1LineDataSet);
        lineDatasets.add(rsi2LineDataSet);
        lineDatasets.add(rsi3LineDataSet);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);


        AJData combinedData = new AJData(xVals);


        combinedData.setData(lineData);
        combinedData.setData(new CandleData());
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setLabelCount(3);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setYlabelStatic(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setStartAtZero(false);
        mKLineCombinedChart.setAffilateChartData(combinedData);
        mKLineCombinedChart.setInitScale(xVals);
    }

    private void buildADX(List<ADX> adxList) {

        List<String> xVals = Arrays.asList(new String[adxList.size()]);
        ArrayList<Entry> adxs = new ArrayList<>();
        int count = adxList.size();
        if (count == 0) {
            mKLineCombinedChart.setAffilateChartNoDataText("暂无数据");
            return;
        }
        for (int i = 0; i < adxList.size(); i++) {
            ADX adx = adxList.get(i);
            adxs.add(new Entry(adx.adx, i, adx));
        }
        LineDataSet adxLineDataSet = new LineDataSet(adxs, "adx");
        setLineDateSetStyle(adxLineDataSet);
        adxLineDataSet.setColor(getResources().getColor(R.color.rsi1));
        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(adxLineDataSet);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);
        AJData combinedData = new AJData(xVals);
        combinedData.setData(lineData);
        combinedData.setData(new CandleData());
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setLabelCount(3);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setYlabelStatic(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setStartAtZero(false);
        mKLineCombinedChart.setAffilateChartData(combinedData);
    }

    private void buildATR(List<ATR> atrList) {
        List<String> xVals = Arrays.asList(new String[atrList.size()]);
        ArrayList<Entry> atrs = new ArrayList<>();
        int count = atrList.size();
        if (count == 0) {
            mKLineCombinedChart.setAffilateChartNoDataText("暂无数据");
            return;
        }
        for (int i = 0; i < atrList.size(); i++) {
            ATR atr = atrList.get(i);
            atrs.add(new Entry(atr.atr, i, atr));
        }
        LineDataSet atrLineDataSet = new LineDataSet(atrs, "atr");
        setLineDateSetStyle(atrLineDataSet);
        atrLineDataSet.setColor(getResources().getColor(R.color.atr));
        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(atrLineDataSet);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);
        AJData combinedData = new AJData(xVals);
        combinedData.setData(lineData);
        combinedData.setData(new CandleData());
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setLabelCount(3);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setYlabelStatic(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setStartAtZero(false);
        mKLineCombinedChart.setAffilateChartData(combinedData);
    }

    private void buildVol(List<MinutesData> minutesDatas) {
        final KLineChart affilateChart = mKLineCombinedChart.getAffilateChart();
        //affilateChart.getAxisLeft().setDrawGridLines(false);

        affilateChart.getAxisLeft().setStartAtZero(true);


        affilateChart.getAxisLeft().enableGridDashedLine(3.0f, 3.0f, 3.0f);
        affilateChart.getAxisLeft().setDrawGridLines(true);


//        ArrayList<MinutesData> minutesDatas = kLineDatas.getBarData();
        int count = minutesDatas.size();

        List<String> xVals = Arrays.asList(new String[count]);
        ArrayList<BarEntry> barEntries = new ArrayList<>();
        float max = 0;
        for (int i = 0; i < count; i++) {
            MinutesData minutesData = minutesDatas.get(i);
            barEntries.add(new BarEntry(minutesData.chengjiaoliang, i, minutesData));
            max = Math.max(max, minutesData.chengjiaoliang);
        }

        BarDataSet barDataset = new BarDataSet(barEntries, "成交量");
        barDataset.setColor(getResources().getColor(R.color.main_text));
        barDataset.setAxisDependency(YAxis.AxisDependency.LEFT);

        AJData marketData = new AJData(xVals);
        BarData barData = new BarData(xVals, barDataset);
        marketData.setData(barData);
        mKLineCombinedChart.setAffilateChartData(marketData);
        mKLineCombinedChart.setInitScale(xVals);

    }

    private void buildDMI(List<DMI> dmisList) {

        List<String> xVals = Arrays.asList(new String[dmisList.size()]);
        ArrayList<Entry> adxs = new ArrayList<>();


        int count = dmisList.size();

        if (count == 0) {
            mKLineCombinedChart.setAffilateChartNoDataText("暂无数据");
            return;
        }
        for (int i = 0; i < dmisList.size(); i++) {
            DMI adx = dmisList.get(i);
            adxs.add(new Entry(adx.adx, i, adx));

        }


        LineDataSet adxLineDataSet = new LineDataSet(adxs, "adx");

        setLineDateSetStyle(adxLineDataSet);

        adxLineDataSet.setColor(getResources().getColor(R.color.rsi1));


        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(adxLineDataSet);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);
        AJData combinedData = new AJData(xVals);
        combinedData.setData(lineData);
        combinedData.setData(new CandleData());
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setLabelCount(3);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setYlabelStatic(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setStartAtZero(false);
        mKLineCombinedChart.setAffilateChartData(combinedData);
        mKLineCombinedChart.setInitScale(xVals);
    }

    private void buildRSI(List<List<RSI>> rsiList) {

        List<String> xVals = Arrays.asList(new String[rsiList.get(0).size()]);
        ArrayList<Entry> rsi1 = new ArrayList<>();
        ArrayList<Entry> rsi2 = new ArrayList<>();
        ArrayList<Entry> rsi3 = new ArrayList<>();


        int count = rsiList.size();

        if (count == 0) {
            mKLineCombinedChart.setAffilateChartNoDataText("暂无数据");
            return;
        }
        for (int i = 0; i < rsiList.get(0).size(); i++) {
            RSI r1 = rsiList.get(0).get(i);
            RSI r2 = rsiList.get(1).get(i);
            RSI r3 = rsiList.get(2).get(i);
            rsi1.add(new Entry(r1.rsi1, i, r1));
            rsi2.add(new Entry(r2.rsi1, i, r2));
            rsi3.add(new Entry(r3.rsi1, i, r3));

        }


        LineDataSet rsi1LineDataSet = new LineDataSet(rsi1, "rsi1");
        LineDataSet rsi2LineDataSet = new LineDataSet(rsi2, "rsi2");
        LineDataSet rsi3LineDataSet = new LineDataSet(rsi3, "rsi3");

        setLineDateSetStyle(rsi1LineDataSet);
        setLineDateSetStyle(rsi2LineDataSet);
        setLineDateSetStyle(rsi3LineDataSet);

        rsi1LineDataSet.setColor(getResources().getColor(R.color.rsi1));
        rsi2LineDataSet.setColor(getResources().getColor(R.color.rsi2));
        rsi3LineDataSet.setColor(getResources().getColor(R.color.rsi3));


        ArrayList<LineDataSet> lineDatasets = new ArrayList<>();
        lineDatasets.add(rsi1LineDataSet);
        lineDatasets.add(rsi2LineDataSet);
        lineDatasets.add(rsi3LineDataSet);
        LineData lineData = new LineData(xVals, lineDatasets);
        lineData.setDrawValues(false);


        AJData combinedData = new AJData(xVals);


        combinedData.setData(lineData);
        combinedData.setData(new CandleData());
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setLabelCount(3);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setYlabelStatic(true);
        mKLineCombinedChart.getAffilateChart().getAxisLeft().setStartAtZero(false);
        mKLineCombinedChart.setAffilateChartData(combinedData);
        mKLineCombinedChart.setInitScale(xVals);
    }

    /**
     * 控制顶部的view中数据的更新，0.5秒取一次数据
     */
    private CountDownTimer quoteStockTimer = new CountDownTimer(24 * 60 * 60 * 1000, 500) {

        @Override
        public void onTick(long millisUntilFinished) {
            try {
                if (selectXIndex == dataBeanList.size() - 1) {
                    QuoteKLineBean.DataBean dataBean = dataBeanList.get(0);
                    syncTopHighView(selectXIndex, dataBean);
                }
            } catch (Exception e) {
//                ToastUtil.show(context, "网络请求失败，请稍后重试");
            }
        }

        @Override
        public void onFinish() {
        }
    };

    @Override
    public void unRegister() {
        super.unRegister();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        if (mKLineCombinedChart != null) {
            mKLineCombinedChart.clearChart();
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        if (mKLineCombinedChart != null) {
            mKLineCombinedChart.clearChart();
        }
    }
}
